//
//  AppDelegate.m
//  iOS_AVPlayer
//
//  Created by Scott on 16/2/9.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "PlayerViewController.h"
#import <AVFoundation/AVFoundation.h>

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height


@interface PlayerViewController ()


@property(nonatomic,assign)BOOL isPlay;


@property (strong, nonatomic) IBOutlet UIView *playerView;

@property(nonatomic,retain)AVPlayer *player;
@property(nonatomic,retain)AVPlayerLayer *playerLayer;
@property(nonatomic,retain)AVPlayerItem *playerItem;

@property (strong, nonatomic) IBOutlet UISlider *ProgressSlider;

- (IBAction)ProgressAction:(id)sender;

@property (nonatomic, assign) CGFloat totalMovieDuration;//  保存该视频资源的总时长，快进或快退的时候要用
- (IBAction)playButton:(id)sender;

@property (strong, nonatomic) IBOutlet UIView *bottomView;

@property(nonatomic,assign)BOOL isTap;

@property (strong, nonatomic) IBOutlet UIButton *playerButton;
@property (strong, nonatomic) IBOutlet UILabel *timeLabel;

@end

@implementation PlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    //初始化播放器
    [self addAVPlayer];
    //播放
    [self.player play];
    //添加通知
    [self addNotificationCenters];

    //添加进度观察
    [self addProgressObserver];
    
    //添加手势
    [self addGestureRecognizer];

    self.timeLabel.text = @"00:00/00:00";
}


//  播放页面添加轻拍手势
- (void)addGestureRecognizer {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAllSubViews)];
    [self.view addGestureRecognizer:tap];
}

//隐藏bottomView
-(void)dismissAllSubViews
{

    if (self.isTap == NO) {

        [UIView animateWithDuration:0.5 animations:^{

            self.bottomView.alpha = 0;
            
        }];
    }else
    {
        [UIView animateWithDuration:0.5 animations:^{
            self.bottomView.alpha = 0.5;

        }];
    }
    self.isTap = !self.isTap;
}

-(void)addAVPlayer
{
    //urlStr = @"http://flv2.bn.netease.com/videolib3/1505/24/HYUCE6348/SD/HYUCE6348-mobile.mp4";

    NSString *urlStr=[NSString stringWithFormat:@"http://flv2.bn.netease.com/videolib3/1505/24/HYUCE6348/SD/HYUCE6348-mobile.mp4"];
    urlStr =[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url=[NSURL URLWithString:urlStr];
    //创建视频项目对象
    self.playerItem = [[AVPlayerItem alloc] initWithURL:url];
    //创建视频播放器对象
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    //创建承载播放器的AVPlayerLayer对象
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = CGRectMake(5, 5, SCREEN_WIDTH - 10, self.playerView.frame.size.height-5);
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;//视频填充模式
    //将播放器添加到playerView的layer层上
    [self.playerView.layer insertSublayer:self.playerLayer atIndex:0];

    self.playerView.backgroundColor = [UIColor whiteColor];

}

#pragma mark - 观察者 观察播放完毕 观察屏幕旋转
- (void)addNotificationCenters {
    //  注册观察者用来观察，是否播放完毕
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    //  注册观察者来观察屏幕的旋转
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}

#pragma mark 播放结束后的代理回调
- (void)moviePlayDidEnd:(NSNotification *)notify
{

    NSLog(@"播放结束触发");

}

#pragma mark - 横屏 竖屏的时候frame的设置
- (void)statusBarOrientationChange:(NSNotification *)notification {
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationLandscapeRight) {

        NSLog(@"向右横屏");
        [self setPlayerLayerFrame];
    }
    if (orientation == UIInterfaceOrientationLandscapeLeft) {

        NSLog(@"向左横屏");
        [self setPlayerLayerFrame];

    }
    if (orientation == UIInterfaceOrientationPortrait) {

        NSLog(@"竖屏");
        [self setVerticalFrame];
    }
}

//  横屏的时候frame
- (void)setPlayerLayerFrame {

    self.playerLayer.frame = CGRectMake(5, 5, SCREEN_WIDTH - 10, self.playerView.frame.size.height-5);
}

//  竖屏的时候frame
- (void)setVerticalFrame {

    self.playerLayer.frame = CGRectMake(5, 5, SCREEN_WIDTH - 10, self.playerView.frame.size.height-5);

}

/*
 CMTimeMake是用來建立CMTime用的,
 CMTime可是专门用来表示视频时间的,
 用法: CMTimeMake(time, timeScale)

 time指的就是时间(不是秒),
 而时间要换成秒就要看第二个参数timeScale了.
 timeScale指的是1秒需要由多少帧率构成,
 真正表示时间秒是 time / timeScale .

 CMTime curFrame = CMTimeMake(第几帧， 帧率）

 */


#pragma mark -  添加进度观察 - addProgressObserver
- (void)addProgressObserver {
    __block typeof(self) weakSelf = self;
    //设置(1,1) 设置每秒执行一次
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue: dispatch_get_main_queue() usingBlock:^(CMTime time) {

        //总时长 将CMTime类型转成float类型
        CGFloat duration = CMTimeGetSeconds(weakSelf.playerItem.duration);
        //当前时间
       CGFloat current = CMTimeGetSeconds(weakSelf.player.currentTime);
        //倒计时
        CGFloat rem = duration - current;

        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60 ,(int)rem%60];
        NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)current/60 ,(int)current%60];

        NSString *timeStr = [NSString stringWithFormat:@"%@/%@",currenT,totalT];
        weakSelf.timeLabel.text = timeStr;

        //保存总时长用于手动快进和快退
        weakSelf.totalMovieDuration = duration;
        //设置进度值 当前时间/总时长
        weakSelf.ProgressSlider.value = current/duration;

    }];

}

- (IBAction)ProgressAction:(id)sender {

    UISlider *slider = sender;
    //获取当前时间
    double currentTime = self.totalMovieDuration * slider.value;
    CMTime dragedCMTime = CMTimeMake(currentTime, 1);
    [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {

        [self.player play];

    }];

}

- (IBAction)playButton:(id)sender {

    if (self.isPlay) {

        [self.player pause];
    }else
    {
        [self.player play];
    }
    self.isPlay = !self.isPlay;
}
@end
